/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.adaptive.create;

import com.facebook.airlift.log.Logger;
import com.facebook.presto.adaptive.AdaptiveUtil;
import com.facebook.presto.spi.adaptive.CatalogEngine;
import com.facebook.presto.sql.tree.CreateTable;
import com.facebook.presto.sql.tree.Expression;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.facebook.presto.spi.adaptive.AdaptiveConstant.TABLE_PROPERTY_CATALOG;
import static com.facebook.presto.sql.NodeUtils.mapFromProperties;

public class HintCreator
        implements AdaptiveCreator
{
    public static final Logger log = Logger.get(HintCreator.class);

    @Override
    public List<CatalogEngine> selectCreator(CreateTable statement)
    {
        Map<String, Expression> sqlProperties = mapFromProperties(statement.getProperties());
        try {
            String hintCatalogStr = sqlProperties.get(TABLE_PROPERTY_CATALOG).toString();
            hintCatalogStr = hintCatalogStr.substring(1, hintCatalogStr.length() - 1);
            List<String> hintCatalogList = Arrays.asList(hintCatalogStr.split("\\|"));
            return changeToCatalogEngineList(hintCatalogList);
        }
        catch (Exception ex) {
            return new ArrayList<>();
        }
    }

    /**
     * Convert a list of strings to a list of catalog engines
     * @param hintCatalogList
     * @return
     */
    private List<CatalogEngine> changeToCatalogEngineList(List<String> hintCatalogList)
    {
        if (hintCatalogList == null || hintCatalogList.isEmpty()) {
            return new ArrayList<>();
        }
        log.info("Adaptive creator - Select Engine, HintCreator selects %s engine.", hintCatalogList);
        return hintCatalogList.stream()
                .map(AdaptiveUtil::changeToCatalogEngine)
                .collect(Collectors.toList());
    }
}
